﻿#include "Tucamwidget.h"
#include "ui_Tucamwidget.h"


//调用摄像头
#include <QCameraInfo>
#include <QCamera>
#include <QCameraViewfinder>
#include <QCameraImageCapture>
#include <QPixmap>
//弹窗
#include <QMessageBox>
#include <QDebug>

#include <QPixmap>
#include <QImage>
//裁剪
#include <QDesktopWidget>
#include <QMouseEvent>
#include <QPainter>

static const char* m_strArrCapa[]  = { "TUIDC_RESOLUTION          : [Resolution]                 ",
"TUIDC_PIXELCLOCK          : [Pixel Clock]                ",
"TUIDC_BITOFDEPTH          : [Bit Of Depth]               ",
"TUIDC_ATEXPOSURE          : [Auto Exposure]              ",
"TUIDC_HORIZONTAL          : [Horizontal]                 ",
"TUIDC_VERTICAL            : [Vertical]                   ",
"TUIDC_ATWBALANCE          : [Auto White Balance]         ",
"TUIDC_FAN_GEAR            : [Fan Gear]                   ",
"TUIDC_ATLEVELS            : [Auto Levels]                ",
"TUIDC_SHIFT               : [Shift]                      ",
"TUIDC_HISTC               : [Histogram Statistic]        ",
"TUIDC_CHANNELS            : [Current Channel]            ",
"TUIDC_ENHANCE             : [Enhance]                    ",
"TUIDC_DFTCORRECTION       : [Defect Correction]          ",
"TUIDC_ENABLEDENOISE       : [Enable Denoise]             ",
"TUIDC_FLTCORRECTION       : [Flat Field Correction]      ",
"TUIDC_RESTARTLONGTM       : [Restart Long Time]          ",
"TUIDC_DATAFORMAT          : [Data format]                ",
"TUIDC_DRCORRECTION        : [Dynamic Range Of Correction]",
"TUIDC_VERCORRECTION       : [Vertical Correction]        ",
"TUIDC_MONOCHROME          : [Monochromatic]              ",
"TUIDC_BLACKBALANCE        : [Black Balance]              ",
"TUIDC_IMGMODESELECT       : [Image mode(CMS)]            ",
"TUIDC_CAM_MULTIPLE        : [Multiple Cameras]           ",
"TUIDC_ENABLEPOWEEFREQUENCY: [Enable Power frequency]     ",
"TUIDC_ROTATE_R90          : [Rotate Right 90°]          ",
"TUIDC_ROTATE_L90          : [Rotate Left 90°]           ",
"TUIDC_NEGATIVE            : [Enable Negative Film]       ",
"TUIDC_HDR                 : [Enable HDR]                 ",
"TUIDC_ENABLEIMGPRO        : [Enable Image Process]       ",
"TUIDC_ENABLELED           : [Enable USB Led]             ",
"TUIDC_ENABLETIMESTAMP     ; [Enable Time Stamp]          ",
"TUIDC_ENABLEBLACKLEVEL    : [Enable Black Level]         " "TUIDC_ATFOCUS             : [Auto Focus Enable]          ",
"TUIDC_ATFOCUS_STATUS      : [Auto Focus Status]          ",
"TUIDC_PGAGAIN             : [Sensor PGA Gain]            ",
"TUIDC_ATEXPOSURE_MODE     : [Automatic Exposure Time Mode]",
"TUIDC_BINNING_SUM         : [Summation Binning]          ",
"TUIDC_BINNING_AVG         : [Average Binning]            ",
"TUIDC_FOCUS_C_MOUNT       : [Focus c-mount Mode]         ",
"TUIDC_ENABLEPI            : [PI Enable]                  ",
"TUIDC_ATEXPOSURE_STATUS   : [Auto Exposure Status]       ",
"TUIDC_ATWBALANCE_STATUS   : [Auto WhiteBalance Status]   ",
"TUIDC_TESTIMGMODE         : [Test Image Mode Select]     ",
"TUIDC_SENSORRESET         : [Sensor Reset]               ",
"TUIDC_PGAHIGH             : [PGA High Gain]              ",
"TUIDC_PGALOW              : [PGA Low Gain]               ",
"TUIDC_PIXCLK1_EN          : [Pix2 Clock Enable]          ",
"TUIDC_PIXCLK2_EN          : [Pix1 Clock Enable]          ",
"TUIDC_ATLEVELGEAR         : [Auto Level Gear]            ",
"TUIDC_ENABLEDSNU          : [Enable DSNU]                ",
"TUIDC_ENABLEOVERLAP       : [Enable Exposure Time Overlap Mode]       ",
"TUIDC_CAMSTATE            : [Camera State]               ",
"TUIDC_ENABLETRIOUT        ; [Enable Trigger Out]         ",
"TUIDC_ROLLINGSCANMODE     : [Rolling Scan Mode]          ",
"TUIDC_ROLLINGSCANLTD      : [Rolling Scan Line Time Delay] ",
"TUIDC_ROLLINGSCANSLIT     : [Rolling Scan Slit Height]     ",
"TUIDC_ROLLINGSCANDIR      : [Rolling Scan Direction]       ",
"TUIDC_ROLLINGSCANRESET    : [Rolling Scan Direction Reset] ",
"TUIDC_ENABLETEC           : [Tec Enable]                   ",
"TUIDC_ENABLEBLC           : [Backlight Compensation Enable]",
"TUIDC_ENABLETHROUGHFOG    : [Electronic Through Fog Enable]",
"TUIDC_ENABLEGAMMA         : [Gamma Enable]                 ",
"TUIDC_ENABLEFILTER        ; [Filter Enable]                ",
"TUIDC_ENABLEHLC           : [Strong Light Inhibition Enable]         ",
"TUIDC_CAMPARASAVE         : [Camera Pamameter Save]       ",
"TUIDC_CAMPARALOAD         : [Camera Parameter Load]       ",
"TUIDC_ENABLEISP           : [Isp Enable]                  ",
"TUIDC_BUFFERHEIGHT        : [Buffer Height]               ",
"TUIDC_VISIBILITY          ; [Visibility]                  ",
"TUIDC_SHUTTER             : [Shutter Mode]                ",
"TUIDC_SIGNALFILTER        ; [Signal Filter]               "
};
static const char* m_strArrProp[]  = { "TUIDP_GLOBALGAIN      : [Global Gain]                ",
"TUIDP_EXPOSURETM      : [Exposure Time]              ",
"TUIDP_BRIGHTNESS      : [Brightness(Auto Exposure)]  ",
"TUIDP_BLACKLEVEL      : [Black Level]                ",
"TUIDP_TEMPERATURE     : [Temperature]                ",
"TUIDP_SHARPNESS       : [Sharpness]                  ",
"TUIDP_NOISELEVEL      : [Noise Level]                ",
"TUIDP_HDR_KVALUE      : [HDR K Value]                ",
"TUIDP_GAMMA           : [Gamma]                      ",
"TUIDP_CONTRAST        : [Contrast]                   ",
"TUIDP_LFTLEVELS       : [Left Levels]                ",
"TUIDP_RGTLEVELS       : [Right Levels]               ",
"TUIDP_CHNLGAIN        : [Channel Gain]               ",
"TUIDP_SATURATION      : [Saturation]                 ",
"TUIDP_CLRTEMPERATURE  : [Color Temperature]          ",
"TUIDP_CLRMATRIX       : [Color Matrix]               ",
"TUIDP_DPCLEVEL        : [DPC Level]                  ",
"TUIDP_BLACKLEVELHG    : [Black Level High Gain]      ",
"TUIDP_BLACKLEVELLG    : [Black Level Low Gain]       ",
"TUIDP_POWEEFREQUENCY  : [Power frequency]            ",
"TUIDP_HUE             : [Hue]                        ",
"TUIDP_LIGHT           : [Light]                      ",
"TUIDP_ENHANCE_STRENGTH: [Enhance strength]           ",
"TUIDP_NOISELEVEL_3D   : [Noise Level 3D]             ",
"TUIDP_FOCUS_POSITION  : [Position]                   ",
"TUIDP_FRAME_RATE      : [Frame Rate]                 ",
"TUIDP_START_TIME      : [Start Time]                 ",
"TUIDP_FRAME_NUMBER    : [Frame Number]               ",
"TUIDP_INTERVAL_TIME   : [Interval Time]              ",
"TUIDP_GPS_APPLY       : [GPS Apply]                  ",
"TUIDP_AMB_TEMPERATURE : [Amb Temperature]            ",
"TUIDP_AMB_HUMIDITY    : [Amb Humidity]               ",
"TUIDP_AUTO_CTRLTEMP   : [Auto Control Temperature]   ",
"TUIDP_AVERAGEGRAY     : [Average]                    ",
"TUIDP_AVERAGEGRAYTHD  : [Average Gray Thd]           ",
"TUIDP_ENHANCETHD      : [Enhance Threshold ]         ",
"TUIDP_ENHANCEPARA     : [Enhance Parameter]          ",
"TUIDP_EXPOSUREMAX     : [Exposure Max]               ",
"TUIDP_EXPOSUREMIN     : [Exposure Min]               ",
"TUIDP_GAINMAX         : [Gain Max]                   ",
"TUIDP_GAINMIN         : [Gain Min]                   ",
"TUIDP_THROUGHFOGPARA  : [Through Fog]                ",
"TUIDP_ATLEVEL_PERCENTAGE   : [Auto Level Ignore]     ",
"TUIDP_TEMPERATURE_TARGET   : [Temperature Target]    ",
"TUIDP_PIXELRATIO      : [pixel ratio]                ",
};

TucamWidget::TucamWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::TucamWidget)
{
    ui->setupUi(this);

  o.show();//打开子窗口
  initialize();//初始化
  opencam();//打开摄像头
  btn_preView();//打开预览

 rect = ui->cameraView->geometry();
 qreal scaleFactor = ui->cameraView->devicePixelRatio(); // 获取DPI缩放因子
 displayWidth = rect.width() * scaleFactor;
 displayHeight = rect.height() * scaleFactor;
    // 获取显示区域的尺寸
//    rect = ui->cameraView->geometry();
//    displayWidth = rect.width();
//    displayHeight = rect.height();

     //创建线程
   cameraThread=new QThread(this);//线程实例化
   cameraWorker=new CameraWorker;//子线程类实例化
   cameraWorker->moveToThread(cameraThread);//将子对象移动到线程中
   cameraThread->start();

   //初始化曝光滑动条
   initalSlider();
   qDebug()<<"stepvalues:"<<stepValues.size();
    qDebug()<<"stepvalues:"<<stepValues;
   ui->Slider_exposure->setRange(0,stepValues.size() - 1);
   ui->Slider_exposure->setValue(0);
   ui->Slider_exposure->setPageStep(1);

   // 创建 QButtonGroup 来管理ROI按钮
   buttonGroup = new QButtonGroup(this);
   buttonGroup->addButton(ui->ROI_pre_btn);
   buttonGroup->addButton(ui->ROI_manual_btn);
   buttonGroup->setExclusive(true);                     // 设置按钮互斥模式
   connect(ui->ROI_pre_btn, &QRadioButton::toggled, this, &TucamWidget::on_ROI_pre_selected);
   connect(ui->ROI_manual_btn, &QRadioButton::toggled, this, &TucamWidget::on_ROI_manual_selected);
   ui->ROI_pre_btn->setChecked(true);                   // 默认选中"预置"按钮

   // roi对象赋初始值
   roi.bEnable = false;
   roi.nHOffset = 0;
   roi.nVOffset = 0;
   roi.nWidth = 3000;
   roi.nHeight = 3000;

   refreshTemperature = new QTimer(this);
   refreshExposureTime = new QTimer(this);
   connect(refreshTemperature, &QTimer::timeout, this, &TucamWidget::currentTemperature);
   connect(refreshExposureTime, &QTimer::timeout, this, &TucamWidget::currentExposureTime);
   // 将信号与槽连接
   connect(this, &TucamWidget::StratTread, cameraWorker, &CameraWorker::ThreadStart);
   connect(this, &TucamWidget::stopCameraWorker, cameraWorker, &CameraWorker::stop);
   connect(cameraWorker, &CameraWorker::frameReady, this, &TucamWidget::updateLabel,Qt::BlockingQueuedConnection);

   // 确保在退出时清理线程
   connect(cameraThread, &QThread::finished, cameraWorker, &QObject::deleteLater);//子线程释放

   //裁剪槽函数
   connect(this, &TucamWidget::cropCompleted, this, &TucamWidget::handleCropCompleted);
   connect(this, &TucamWidget::cropCanceled, this, &TucamWidget::handleCropCanceled);
   ui->picture->lower(); // 将QLabel置于父控件底层
   ui->picture->setAttribute(Qt::WA_TranslucentBackground); // 允许父控件绘制穿透
   ui->picture->setAttribute(Qt::WA_TransparentForMouseEvents); // 传递鼠标事件

   //调节亮度
   connect(ui->image_brightness_slider, SIGNAL(valueChanged(int)), ui->image_brightness, SLOT(setValue(int)));
   connect(ui->image_brightness, SIGNAL(valueChanged(int)), ui->image_brightness_slider, SLOT(setValue(int)));
   //对比度进行连接
   connect(ui->image_contrast_slider, SIGNAL(valueChanged(int)), ui->image_contrast, SLOT(setValue(int)));
   connect(ui->image_contrast, SIGNAL(valueChanged(int)), ui->image_contrast_slider, SLOT(setValue(int)));
   //窗口的转换
   connect(&o, &open::opentuc, this, &TucamWidget::change);
}

TucamWidget::~TucamWidget()
{
    refreshTemperature->stop();

    if (refreshExposureTime->isActive()) {
        refreshExposureTime->stop();
    }
    cameraThread->quit();
    cameraThread->wait();
    delete ui;
}
//初试化
void TucamWidget::initialize()
{
    if (!initializeCamera()) {
        qDebug()<<"init the camera failure\r\n";
    }

    else
    {
        qDebug()<<"init the camera success\r\n";

    }

   qDebug()<<"Press any key to exit...\r\n";

}

void TucamWidget::btn_preView()
{  if (if_inital) {
        if (TUCAM_Cap_Start(m_opCam.hIdxTUCam, (UINT32)TUCCM_SEQUENCE) != TUCAMRET_SUCCESS) {
            qDebug() << "Failed to start capturing.";
            return;
        }
        qDebug() << "success to start capturing.";


        // 将摄像头句柄传递给工作线程
        cameraWorker->setCameraHandle(m_opCam, m_frame);

        // 启动线程
        emit StratTread();
       }

    else
    {
        qDebug()<<"init the camera failure\r\n";
    }
}

void TucamWidget::on_colseCamera_clicked()
{

    cameraManager->CloseCamera();

    TUCAM_Buf_Release(m_opCam.hIdxTUCam);
    cameraManager->UninitApi();
     if_inital=false;
}

void TucamWidget::opencam()
{

    if (if_inital) {
        //设置相机id
          m_opCam.uiIdxOpen = ui->comboBox_select_camera->currentIndex();
          if (TUCAM_Dev_Open(&m_opCam) != TUCAMRET_SUCCESS) {
              qDebug() << "Failed to open camera.";

          }
           refreshTemperature->start(300);


          TUCAM_VALUE_INFO valInfo;
          valInfo.nID = TUIDI_PRODUCT;
          TUCAM_Dev_GetInfo(m_opCam.hIdxTUCam, &valInfo);
          m_nPID = valInfo.nValue;

          //相机拍摄格式
          m_frame.pBuffer = nullptr;
          m_frame.ucFormatGet = TUFRM_FMT_USUAl;
          m_frame.uiRsdSize = 1;

          //TUCAM_Capa_SetValue(m_opCam.hIdxTUCam, TUIDC_HORIZONTAL, 0);
          //垂直翻转
          TUCAM_Capa_SetValue(m_opCam.hIdxTUCam, TUIDC_VERTICAL, 0);
          //增益
          TUCAM_Prop_SetValue(m_opCam.hIdxTUCam, TUIDP_GLOBALGAIN, 1);


            drawInit.hWnd = reinterpret_cast<HWND>(ui->cameraView->winId());

            // 设置图像的通道数（根据实际数据格式，通常为 1 或 3）
            drawInit.ucChannels = 1;  // 假设单通道灰度图

            // 设置图像宽度和高度（根据实际分辨率）
            drawInit.nWidth = 3000;   // 替换为实际宽度
            drawInit.nHeight = 3000;  // 替换为实际高度

            //初始化图像绘制
            if (TUCAM_Draw_Init(m_opCam.hIdxTUCam, drawInit) != TUCAMRET_SUCCESS) {
                qDebug() << "Failed to initialize TUCAM drawing!";
            }


            if (TUCAM_Buf_Alloc(m_opCam.hIdxTUCam, &m_frame) != TUCAMRET_SUCCESS) {
                qDebug() << "Failed to allocate buffer.";

            }


            TUCAM_VALUE_INFO valInfo1;
            valInfo.nID = TUIDI_ZEROTEMPERATURE_VALUE;
            TUCAM_Dev_GetInfo(m_opCam.hIdxTUCam, &valInfo1);

            m_nMidTTemp = valInfo1.nValue;
             qDebug()<<"Open the camera success\r\n";
    }


       else
       {
           qDebug()<<"init the camera failure\r\n";
       }
}


void TucamWidget::updateLabel(const TUCAM_FRAME& frame)
{
//qDebug() << "recive frame";
memcpy(&capframe, &frame, sizeof(TUCAM_FRAME));
       // 计算缩放比例和偏移量
       float scaleX = displayWidth * 1.0f / frame.usWidth;
       float scaleY = displayHeight * 1.0f / frame.usHeight;

       float scale = qMin(scaleX, scaleY); // 按比例缩放
       int drawWidth = scale * frame.usWidth;
       int drawHeight = scale * frame.usHeight;

       int offsetX = (displayWidth - drawWidth) / 2;
       int offsetY = (displayHeight - drawHeight) / 2;

            if(NULL!=frame.pBuffer)
            {

               
                  drawing.pFrame = const_cast<TUCAM_FRAME*>(&frame);
                  drawing.nDstX = offsetX;
                  drawing.nDstY = offsetY;
                  drawing.nDstWidth = drawWidth;
                  drawing.nDstHeight = drawHeight;
                  drawing.nSrcX = 0;
                  drawing.nSrcY = 0;
                  drawing.nSrcWidth = frame.usWidth;
                  drawing.nSrcHeight = frame.usHeight;

          TUCAM_Draw_Frame(m_opCam.hIdxTUCam, &drawing);
        }
 }

bool TucamWidget::initializeCamera()
{
       m_itApi.uiCamCount = 0;
       m_itApi.pstrConfigPath = "./";
       TUCAM_VALUE_INFO m_viCam; // Value info object
       m_viCam.nID = (int)TUIDI_CAMERA_MODEL;
       if (TUCAM_Api_Init(&m_itApi) != TUCAMRET_SUCCESS || m_itApi.uiCamCount == 0) {
           qDebug() << "Failed to initialize TUCam API or no camera connected.";
           return false;
       }

       ui->comboBox_select_camera->clear();
       ui->comboBox_resolution->clear();

       for (unsigned int i = 0; i < m_itApi.uiCamCount; ++i) {
           //char cameraName[256] = {0};

           if(TUCAM_Dev_GetInfoEx(i, &m_viCam)== TUCAMRET_SUCCESS){
               QString name = m_viCam.pText;
            // QString id=m_viCam.nID;
               //qDebug() << "Camera id detected:" << id;
               qDebug() << "Camera detected:" << name;
               ui->comboBox_select_camera->addItem(name);   // 添加到 comboBox

               if_inital=true;
           } else {
               qDebug() << "Failed to retrieve name for camera index:" << i;
               if_inital=false;
           }
       }


}

void TucamWidget::on_stopcap_clicked()
{
    qDebug() << "send stop";

    emit stopCameraWorker(); // 通知工作线程停止

}
void TucamWidget::on_ROI_pre_selected(bool checked)
{
    if (checked) {
        qDebug() << "ROI Pre option is selected.";
        QString degreeText = ui->ROI_degree_comboBox->currentText();
        if(degreeText=="1/2"){
            roi.bEnable = true;
            roi.nHOffset = 748;
            roi.nVOffset = 748;
            roi.nWidth = 1500;
            roi.nHeight = 1500;
        }else if (degreeText=="1/4") {
            roi.bEnable = true;
            roi.nHOffset = 1124;
            roi.nVOffset = 1124;
            roi.nWidth = 748;
            roi.nHeight = 748;
        }else if (degreeText=="1/8") {
            roi.bEnable = true;
            roi.nHOffset = 1312;
            roi.nVOffset = 1312;
            roi.nWidth = 372;
            roi.nHeight = 372;
        }else {
            roi.bEnable = true;
            roi.nHOffset = 0;
            roi.nVOffset = 0;
            roi.nWidth = 3000;
            roi.nHeight = 3000;
        }

       TUCAM_Cap_SetROI(m_opCam.hIdxTUCam, roi);

//       emit stopCameraWorker(); // 通知工作线程停止
       on_stopcap_clicked();

//       qDebug() << "R0.";

//       on_btn_preView_clicked();

//       qDebug() << "R1.";
    }
}


void TucamWidget::on_ROI_manual_selected(bool checked)
{
    if (checked) {
        qDebug() << "ROI Manual option is selected.";
        // 在这里你可以执行其他与 ROI_manual_btn 相关的操作
    }
}

void TucamWidget::on_ROI_set_btn_clicked()
{  if (if_inital) {
        if (TUCAM_Cap_Start(m_opCam.hIdxTUCam, (UINT32)TUCCM_SEQUENCE) != TUCAMRET_SUCCESS) {
            qDebug() << "Failed to start capturing.";
            return;
        }
        qDebug() << "success to start capturing.";


        // 将摄像头句柄传递给工作线程
        cameraWorker->setCameraHandle(m_opCam, m_frame);

        // 启动线程
        emit StratTread();
       }

    else
    {
        qDebug()<<"init the camera failure\r\n";
    }
}

/** --------------@brief：获取属性、性能信息------------- **/

void TucamWidget::on_pushButton_clicked()
{
    TUCAM_CAPA_ATTR capa;
      capa.idCapa = 0;
      capa.nValDft = 0;
      capa.nValMin = 0;
      capa.nValMax = 0;
      capa.nValStep = 0;

      char szRes[64] = { 0 };
      TUCAM_VALUE_TEXT valText;
      valText.nID = 0;
      valText.dbValue = 0;
      valText.nTextSize = 64;
      valText.pText = szRes;

      qDebug() << "Getting capability information list";

      for (int i = static_cast<int>(TUIDC_RESOLUTION); i < static_cast<int>(TUIDC_ENDCAPABILITY); ++i) {
          capa.idCapa = i;

          if (TUCAMRET_SUCCESS == TUCAM_Capa_GetAttr(m_opCam.hIdxTUCam, &capa)) {
              TUCAM_Capa_SetValue(m_opCam.hIdxTUCam, i, capa.nValDft);
              qDebug() << QString("0x%1.%2 Range[%3, %4] Default:%5 Step:%6")
                              .arg(i, 2, 16, QChar('0'))
                              .arg(m_strArrCapa[i])
                              .arg(capa.nValMin)
                              .arg(capa.nValMax)
                              .arg(capa.nValDft)
                              .arg(capa.nValStep);

              if (i == static_cast<int>(TUIDC_RESOLUTION)) {
                  int nCnt = capa.nValMax - capa.nValMin + 1;
                  valText.nID = i;

                  for (int j = 0; j < nCnt; ++j) {
                      valText.dbValue = j;
                      if (TUCAMRET_SUCCESS == TUCAM_Capa_GetValueText(m_opCam.hIdxTUCam, &valText)) {
                          qDebug() << j << ":" << valText.pText;
                      }
                  }
              }
          } else {
              qDebug() << QString("0x%1.%2 Not supported").arg(i, 2, 16, QChar('0')).arg(m_strArrCapa[i]);
          }
      }
      QString resolution = valText.pText;
      ui->comboBox_resolution->addItem(resolution);



}
void TucamWidget::on_pushButton_4_clicked()
{
    double dbVal = 0;

      TUCAM_PROP_ATTR prop;
      prop.idProp = 0;
      prop.nIdxChn = 0;
      prop.dbValDft = 0;
      prop.dbValMin = 0;
      prop.dbValMax = 0;
      prop.dbValStep = 0;

      // 获取属性列表信息
      qDebug() << "Getting property information list";

      for (int i = static_cast<int>(TUIDP_GLOBALGAIN); i < static_cast<int>(TUIDP_ENDPROPERTY); ++i) {
          prop.idProp = i;

          if (TUCAMRET_SUCCESS == TUCAM_Prop_GetAttr(m_opCam.hIdxTUCam, &prop)) {
              qDebug() << QString("ID:0x%1  Name:%2 Range[%3, %4] Default:%5 Step:%6")
                              .arg(i, 2, 16, QChar('0'))
                              .arg(m_strArrProp[i])
                              .arg(prop.dbValMin)
                              .arg(prop.dbValMax)
                              .arg(prop.dbValDft)
                              .arg(prop.dbValStep);
          } else {
              qDebug() << QString("ID:0x%1  Name:%2 Not supported").arg(i, 2, 16, QChar('0')).arg(m_strArrProp[i]);
          }
      }

      qDebug() << "\nSetting property default values";

      for (int i = static_cast<int>(TUIDP_GLOBALGAIN); i < static_cast<int>(TUIDP_ENDPROPERTY); ++i) {
          prop.idProp = i;
          prop.nIdxChn = 0;

          if (TUCAMRET_SUCCESS == TUCAM_Prop_GetAttr(m_opCam.hIdxTUCam, &prop)) {
              if (i == static_cast<int>(TUIDP_CLRTEMPERATURE) ||
                  i == static_cast<int>(TUIDP_HDR_KVALUE) ||
                  i == static_cast<int>(TUIDP_BLACKLEVELHG) ||
                  i == static_cast<int>(TUIDP_BLACKLEVELLG)) {
                  continue; // 特殊属性处理略过
              } else if (i == static_cast<int>(TUIDP_CHNLGAIN)) {
                  // 关闭自动白平衡
                  TUCAM_Capa_SetValue(m_opCam.hIdxTUCam, static_cast<int>(TUIDC_ATWBALANCE), 0);

                  // 设置红色通道
                  TUCAM_Prop_SetValue(m_opCam.hIdxTUCam, i, prop.dbValDft, 1);
                  qDebug() << QString("ID:0x%1  Name:%2 Set default value %3 success (channel red)")
                                  .arg(i, 2, 16, QChar('0'))
                                  .arg(m_strArrProp[i])
                                  .arg(prop.dbValDft);

                  // 设置绿色通道
                  TUCAM_Prop_SetValue(m_opCam.hIdxTUCam, i, prop.dbValDft, 2);
                  qDebug() << QString("ID:0x%1  Name:%2 Set default value %3 success (channel green)")
                                  .arg(i, 2, 16, QChar('0'))
                                  .arg(m_strArrProp[i])
                                  .arg(prop.dbValDft);

                  // 设置蓝色通道
                  TUCAM_Prop_SetValue(m_opCam.hIdxTUCam, i, prop.dbValDft, 3);
                  qDebug() << QString("ID:0x%1  Name:%2 Set default value %3 success (channel blue)")
                                  .arg(i, 2, 16, QChar('0'))
                                  .arg(m_strArrProp[i])
                                  .arg(prop.dbValDft);
              } else {
                  TUCAM_Prop_SetValue(m_opCam.hIdxTUCam, i, prop.dbValDft, 0);
                  qDebug() << QString("ID:0x%1  Name:%2 Set default value %3 success")
                                  .arg(i, 2, 16, QChar('0'))
                                  .arg(m_strArrProp[i])
                                  .arg(prop.dbValDft);
              }
          }
      }

      qDebug() << "\nGetting current property values";



}
//自动曝光
void TucamWidget::on_ATEXPOSURE_check_stateChanged(int state)
{



       if (state == Qt::Checked) {


           TUCAM_Capa_SetValue(m_opCam.hIdxTUCam, TUIDC_ATEXPOSURE, 1);

           ui->sec_spinBox->setEnabled(false);
           ui->ms_spinBox->setEnabled(false);
           //ui->uSec_spinBox->setEnabled(false);//微秒不要
           ui->Slider_exposure->setEnabled(false);
           refreshExposureTime->start(300);

           // label->setText("Checked");
       }

       else {


           if (refreshExposureTime->isActive()) {
               refreshExposureTime->stop();
           }

            TUCAM_Capa_SetValue(m_opCam.hIdxTUCam, TUIDC_ATEXPOSURE, 0);
           //label->setText("Unchecked");
           ui->sec_spinBox->setEnabled(true);
           ui->ms_spinBox->setEnabled(true);
           //ui->uSec_spinBox->setEnabled(true);//微秒不要
           ui->Slider_exposure->setEnabled(true);

       }

}

void TucamWidget::UpdateExposureTimeSpinbox(DWORD dwExp)
{
    if ( m_nPID == 0xEC07 ||  m_nPID== 0xEC09)
    {
        if (dwExp < 137)
            dwExp = 130;

        if (dwExp > 15000000)
            dwExp = 15000000;
    }
    else if ( m_nPID == 0xE407)
    {
        if (dwExp > 14000000)
            dwExp = 14000000;
    }
    else if ( m_nPID == 0xE40A)
    {
        if (dwExp > 12000000)
            dwExp = 12000000;
    }

    //m_uSec = (dwExp / (1000 * 1000)) /*% 60*/;//微秒不要
    m_uMs  = (dwExp / 1000) % 1000;
    m_uUs  = dwExp % 1000;

   // m_ExpSpinboxChange=false;
    ui->sec_spinBox->setValue(m_uSec);
    ui->ms_spinBox->setValue(m_uMs);
    //ui->uSec_spinBox->setValue(m_uUs);//微秒不要

    //ui->Slider_exposure->setValue();
}

void TucamWidget::UpdateExposureTimeSliderbox(DWORD dwExp)
{

}
void TucamWidget::on_sec_spinBox_valueChanged(int arg1)
{
    if(!m_ExpSpinboxChange){
        m_ExpSpinboxChange=true;
        return;
    }
  m_uSec=arg1;
  DWORD dwExp = m_uSec * 1000 + m_uMs;
  //double dblExp = dwExp/ 1.0f;//修改
  double dblExp = static_cast<double>(dwExp); // 高效转为 double


  if (NULL != m_opCam.hIdxTUCam)
  {

      //            attrProp.nIdxChn= 0;                    // 使用默认通道
      //            attrProp.idProp = TUIDP_EXPOSURETM;
      //            TUCAM_Prop_GetAttr(m_opCam.hIdxTUCam, &attrProp);
    //  m_uiExpStep = (UINT)(attrProp.dbValStep * 1000 + 0.5f);

      TUCAM_Prop_SetValue(m_opCam.hIdxTUCam, TUIDP_EXPOSURETM, dblExp);
     // TUCAM_Prop_GetValue(m_opCam.hIdxTUCam, TUIDP_EXPOSURETM, &dblExp);

     // UpdateExposureTimeSpinbox((DWORD)(dblExp * 1000));

     // qDebug()<<"毫秒值"<<dblExp * 1000;
     //  qDebug()<<"微秒值"<<dblExp * 1000;
  }
}

void TucamWidget::on_ms_spinBox_valueChanged(int arg1)
{
    if(!m_ExpSpinboxChange){
        m_ExpSpinboxChange=true;
        return;
    }
  m_uMs=arg1;
  DWORD dwExp = m_uSec * 1000+ m_uMs;
  //double dblExp = dwExp/ 1.0f;//修改
  double dblExp = static_cast<double>(dwExp); // 高效转为 double


  if (NULL != m_opCam.hIdxTUCam)
  {

      TUCAM_Prop_SetValue(m_opCam.hIdxTUCam, TUIDP_EXPOSURETM, dblExp);
    //  TUCAM_Prop_GetValue(m_opCam.hIdxTUCam, TUIDP_EXPOSURETM, &dblExp);

    //  UpdateExposureTimeSpinbox((DWORD)(dblExp * 1000));


  }
}
//微妙不要了
//void TucamWidget::on_uSec_spinBox_textChanged(int arg1)
//{

//    if(!m_ExpSpinboxChange){
//        m_ExpSpinboxChange=true;
//        return;
//    }
//  m_uUs=arg1;
//  DWORD dwExp = m_uSec * 1000 * 1000 + m_uMs * 1000 + m_uUs;
//  double dblExp = dwExp/ 1000.0f;


//  if (NULL != m_opCam.hIdxTUCam)
//  {

//      TUCAM_Prop_SetValue(m_opCam.hIdxTUCam, TUIDP_EXPOSURETM, dblExp);
//     // TUCAM_Prop_GetValue(m_opCam.hIdxTUCam, TUIDP_EXPOSURETM, &dblExp);

//    //  UpdateExposureTimeSpinbox((DWORD)(dblExp * 1000));

//  }

//  }
void TucamWidget::on_Slider_exposure_valueChanged(int value)
{
    double value1 = stepValues[value]; // 获取当前步长值
    double dblExp = value1/ 1000.0f;

        //TUCAM_PROP_ATTR  attrProp;
        if (NULL != m_opCam.hIdxTUCam)
        {



            //TUCAM_Prop_SetValue(m_opCam.hIdxTUCam, TUIDP_EXPOSURETM, dblExp);
          //  TUCAM_Prop_GetValue(m_opCam.hIdxTUCam, TUIDP_EXPOSURETM, &dblExp);

            UpdateExposureTimeSpinbox((DWORD)(dblExp * 1000));


        }
}


void TucamWidget::initalSlider()
{
    // 设置最小值、最大值和指数增长的初始步长
       double minValue = 25;  // 25 微秒
       double maxValue = 1200 * 1e6;     // 3600 秒
       double step = 1168;       // 初始步长
       double ratio = 1.3;      // 步长的增长比率

       stepValues.append(minValue); // 首先加入最小值
       while (step < maxValue)
       {
           stepValues.append(step);
           step *= ratio; // 按比例增长步长
       }
       stepValues.append(maxValue); // 加入最大值
}

void TucamWidget::on_comboBox_currentIndexChanged(int index)
{
    if (NULL != m_opCam.hIdxTUCam)
    {
    TUCAM_Capa_SetValue(m_opCam.hIdxTUCam, TUIDC_FAN_GEAR, index);
    }
}

void TucamWidget::currentTemperature()
{
    double dbVal = 0.0; // 存储温度值
   double targetVal=0.0;
    // 假设 TUCAM_Prop_GetValue 函数返回温度值
    if (TUCAMRET_SUCCESS == TUCAM_Prop_GetValue(m_opCam.hIdxTUCam, TUIDP_TEMPERATURE, &dbVal))
    {

       TUCAM_Prop_GetValue(m_opCam.hIdxTUCam, TUIDP_TEMPERATURE_TARGET, &targetVal);
        // 格式化温度值并显示
        QString szTemp = "0";


            // 使用整数格式显示温度值
           szTemp = QString::number(dbVal, 'f', 1);


        // 设置 QLineEdit 控件的文本为温度值
        ui->current_temp->setText(szTemp);
    }
}

void TucamWidget::currentExposureTime()
{
    m_ExpSpinboxChange  =false;
     double dbVal = 0;

    if (TUCAMRET_SUCCESS == TUCAM_Prop_GetValue(m_opCam.hIdxTUCam, TUIDP_EXPOSURETM, &dbVal))
    {
        UpdateExposureTimeSpinbox((DWORD)(dbVal * 1000));
    }
}


void TucamWidget::on_temperature_spinBox_valueChanged(int arg1)
{
    int targetTemp=(arg1+50)*10;
    if (NULL != m_opCam.hIdxTUCam)
    {
    TUCAM_Prop_SetValue(m_opCam.hIdxTUCam, TUIDP_TEMPERATURE, targetTemp);
    }
    currentTemperature();
}


void TucamWidget::on_select_file_btn_clicked()
{
    // 打开文件夹选择对话框
            QString dir = QFileDialog::getExistingDirectory(this, tr("选择保存路径"), QString(),
                                                            QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);

            // 如果用户选择了路径，则将其填充到 QLineEdit 中
            if (!dir.isEmpty())
            {
                ui->save_path_lineEdit->setText(dir);
            }
}

void TucamWidget::on_capture_btn_clicked()
{
    if (TUCAM_Buf_Alloc(m_opCam.hIdxTUCam, &m_frame) != TUCAMRET_SUCCESS) {
           qDebug() << "Failed to allocate buffer.";

       }
     //  emit startCapture();
       //cameraWorker->capture();

     QString Path =ui->save_path_lineEdit->text();
     QString path = QDir::toNativeSeparators(Path);

      // QString path ="F:\\amanni\\saveImage";

       QDir dir(path);
       if (!dir.exists())
       {
           qDebug() << "Directory does not exist:" << path;
       }
       QString savePath = path + "\\TUCA" + QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
        //QString savePath ="D:\\tucamwidget\\TucamWidget\\image";

       qDebug()<<savePath;

       QByteArray savePathBytes = savePath.toUtf8();
       // 假设帧数据已通过某种方式获取
      // TUCAM_Buf_Alloc(m_opCam.hIdxTUCam, &m_frame);


          //  TUCAM_Cap_Start(m_opCam.hIdxTUCam, (UINT32)TUCCM_SEQUENCE);
            // if (TUCAMRET_SUCCESS == TUCAM_Buf_WaitForFrame(m_opCam.hIdxTUCam, &capframe))
             // {

           TUCAM_FRAME tuframe;

           memcpy(&tuframe, &capframe, sizeof(TUCAM_FRAME));

   //if (m_frame.pBuffer != nullptr) {
   //    qDebug() << "Frame Info: Width =" << tuframe.usWidth
   //             << "Height =" << tuframe.usHeight
   //             << "Header =" << tuframe.usHeader
   //             << "Bytes per Element =" << tuframe.ucElemBytes;

   //    }else{ qDebug()<<"frame为空";}
                   TUCAM_FILE_SAVE fileSave;
                   fileSave.nSaveFmt = TUFMT_TIF;          // 保存为 Tiff 格式
                   fileSave.pFrame = &tuframe;            // 需要保存的帧指针
                   fileSave.pstrSavePath =savePathBytes.data(); // 转换为路径字符串

                   // 调用保存函数
                   if (TUCAMRET_SUCCESS != TUCAM_File_SaveImage(m_opCam.hIdxTUCam, fileSave))
                   {

                       QMessageBox::warning(this, tr("保存失败"), tr("图像保存失败，请检查路径和文件权限！"));

                       qDebug()<<TUCAM_File_SaveImage(m_opCam.hIdxTUCam, fileSave);
                   }
                   else
                   {
                       QMessageBox::information(this, tr("保存成功"), tr("图像已成功保存到：") + savePath);
                   }
}

void TucamWidget::on_ATFOCUS_check__stateChanged(int arg1)
{
    if (arg1 == Qt::Checked) {

        TUCAM_Capa_SetValue(m_opCam.hIdxTUCam, TUIDC_ATFOCUS, 1);
    }

    else {

         TUCAM_Capa_SetValue(m_opCam.hIdxTUCam, TUIDC_ATEXPOSURE, 0);

    }

}

void TucamWidget::on_image_inverted_clicked()
{
       if(ui->picture->pixmap()->isNull())
           qDebug()<<"false";
       else
       {
             QImage image = ui->picture->pixmap()->toImage();
             QImage invertedImage = invertImageColors(image);
             QPixmap pixmapPtr = QPixmap::fromImage(invertedImage);
             ui->picture->setPixmap(pixmapPtr.scaled(ui->picture->size(), Qt::KeepAspectRatio));
       }


}

QImage TucamWidget::invertImageColors(const QImage &inputImage) {
    // 深拷贝一份图片，避免修改原始数据
    QImage outputImage = inputImage.convertToFormat(QImage::Format_ARGB32);

    // 检查图片是否有效
    if (outputImage.isNull()) {
        return QImage();
    }
    for(int i=0; i<=outputImage.width();i++)
        {
            for(int j=0;j<outputImage.height();j++)
            {
                //每个像素点都修改
                QColor pixel = outputImage.pixelColor(i,j);

                int r = pixel.red();
                int g = pixel.green();
                int b = pixel.blue();

                QColor newColor((255-r),(255-g),(255-b));
                outputImage.setPixelColor(i,j,newColor);
            }
        }
       return outputImage;
}

void TucamWidget::on_openfile_clicked()
{
        QString filename=QFileDialog::getOpenFileName(this,tr("Open Image"),QDir::homePath(),tr("(*.tif)\n(*.jpg)\n(*.bmp)\n(*.png)"));   //打开图片文件，选择图片
        qDebug()<<"filename:"<<filename;
        QImage image=QImage(filename).convertToFormat(QImage::Format_ARGB32);   //图片初始化
        originalimage.load(filename);
        originalimage = originalimage.convertToFormat(QImage::Format_ARGB32);
        //QImage originalimage = QImage(filename).convertToFormat(QImage::Format_ARGB32);这样originalimage会认为是局部变脸应该把QImage删掉
        qDebug()<<"originalimage:"<<originalimage;
        qDebug()<<"image:"<<image;
        if(!image.isNull())
        {
            qDebug()<<"Open Image Success!";
            QPixmap pixmap = QPixmap::fromImage(image);

                        // 设置 QLabel 控件的图片
            ui->picture->setPixmap(pixmap.scaled(ui->picture->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
            QLabel* labels[] = {ui->picture1, ui->picture2, ui->picture3, ui->picture4, ui->picture5,ui->picture6};
                //const int labelCount = 6;

                // 从第一个标签开始检查，依次向后复制
                //for (int i = 0; i < labelCount - 1; ++i) {
                    int picture_number = 0;
                    QLabel *currentLabel = labels[picture_number];
                    QLabel *nextLabel = labels[picture_number + 1];

                    // 检查当前标签是否有图片
                    const QPixmap *pixmapPtr =labels[picture_number]->pixmap();
                           if (pixmapPtr && !pixmapPtr->isNull()) {
                           QPixmap currentPixmap = *pixmapPtr;
                        // 将图片复制到下一个标签
                       // labels[i + 1]->setPixmap(currentPixmap.scaled(nextLabel->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
                          nextLabel->setPixmap(pixmap);
                          nextLabel->setScaledContents(true); // 可选：自动缩放图片
                          qDebug() << "已将图片从 picture" << (picture_number+1) << "复制到 picture" << (picture_number+2);
                          picture_number++;
                        // 如果只需要传递一次，可以 break 退出循环
                        //break;
                   }
                           else
                           {

                               currentLabel->setPixmap(pixmap);
                               currentLabel->setScaledContents(true);
                               //break;
                           }
                //}
        }
        else
        {
            qDebug()<<"Open Image Failed!";
            return;
        }
        //初始化亮度
        ui->image_brightness_slider->setValue(0);
        ui->image_brightness->setValue(0);
        ui->image_contrast_slider->setValue(100);
        ui->image_contrast->setValue(100);
}

//左右翻转
void TucamWidget::on_image_flip_horizontal_clicked()
{
    if(ui->picture->pixmap()->isNull())             //存在异常退出的问题
    {          qDebug() << "picture 中没有图片！";
              }
    //定义水平翻转矩阵
        QTransform transform;
        transform.scale(-1, 1);
        QPixmap flippedPixmap = ui->picture->pixmap()->transformed(transform);
        ui->picture->setPixmap(flippedPixmap.scaled(ui->picture->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
}

//上下翻转
void TucamWidget::on_image_flip_vertically_clicked()
{
    if(ui->picture->pixmap()->isNull())             //存在异常退出的问题
    {          qDebug() << "picture 中没有图片！";
               }
    //定义水平翻转矩阵
        QTransform transform;
        transform.scale(1, -1);
        QPixmap flippedPixmap = ui->picture->pixmap()->transformed(transform);
        ui->picture->setPixmap(flippedPixmap.scaled(ui->picture->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
}
//裁剪
//激活函数
void TucamWidget::activate() {
    if (!ui->picture || ui->picture->pixmap()->isNull()) {
            emit cropCanceled();
            return;
        }

        // 获取目标 QLabel 的位置和图片
        const QPixmap *pixmapPtr = ui->picture->pixmap();
        if (pixmapPtr) {
            m_originalPixmap = *pixmapPtr;
        } else {
            qDebug() << "Label 中没有图片！";
            return;
        }

        m_isCropMode = true;
        setFocus();
        grabMouse();
        update();
}

//鼠标事件
//按压时
void TucamWidget::mousePressEvent(QMouseEvent *event) {
    if (m_isCropMode && event->button() == Qt::LeftButton) {

        qDebug() << "[DEBUG] Mouse Press (Widget):" << event->pos();
        qDebug() << "[DEBUG] Mouse Press (Screen):" << event->globalPos();

        m_isMousePress = true;
            // 使用全局坐标避免嵌套widget的影响
            m_beginPoint = event->pos();
            m_endPoint = event->pos();
            update();
        }
}

//移动鼠标时
void TucamWidget::mouseMoveEvent(QMouseEvent *event) {
    if (m_isMousePress) {
           m_endPoint = event->pos();
           update();
       }
}
//松开鼠标时
void TucamWidget::mouseReleaseEvent(QMouseEvent *event) {
    if (m_isCropMode && m_isMousePress && event->button() == Qt::LeftButton) {
           m_isMousePress = false;
           releaseMouse();

           // 计算裁剪区域
           QRect screenRect = QRect(m_beginPoint, m_endPoint).normalized();
           QRect imageRect = convertToImageRect(screenRect);

           if (imageRect.isValid() && !imageRect.isEmpty()) {
               QPixmap cropped = m_originalPixmap.copy(imageRect);
               ui->picture->setPixmap(cropped.scaled(ui->picture->size(), Qt::KeepAspectRatio));
           }

           m_isCropMode = false;
           update();
       }
}
//绘制部分
void TucamWidget::paintEvent(QPaintEvent *event) {
    QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing);

        if (m_isCropMode) {
            // 减少遮罩透明度
            painter.fillRect(QWidget::rect(), QColor(0, 0, 0, 100));

            // 获取图片显示区域
            QRect imageRect = getImageDisplayArea();

            // 绘制细白框（线宽1像素）
            painter.setPen(QPen(Qt::white, 1, Qt::DotLine)); // [!code ++]
            painter.drawRect(imageRect);

            if (m_isMousePress) {
                QRect selected = QRect(m_beginPoint, m_endPoint).normalized();
                QRect validRect = selected.intersected(imageRect);

                // 确保选区有效
                if (validRect.width() > 2 && validRect.height() > 2) { // [!code ++]
                    painter.setPen(QPen(Qt::red, 2));
                    painter.drawRect(validRect);
                    painter.fillRect(validRect, QColor(255, 0, 0, 30));
                }
            }
        }
}
//通过esc退出截屏
void TucamWidget::keyPressEvent(QKeyEvent *event) {
    if (m_isCropMode && event->key() == Qt::Key_Escape) {
            m_isCropMode = false;
            releaseMouse();
            update();
            emit cropCanceled();
        }
}
//获取当前矩形区域
QRect TucamWidget::getImageDisplayArea() const {
    QPoint labelPos = ui->picture->mapToParent(QPoint(0, 0));

        // 考虑父控件的布局边距
        QMargins parentMargins = this->layout()->contentsMargins();
        labelPos += QPoint(parentMargins.left(), parentMargins.top());

        // 计算实际显示尺寸
        QSize contentSize = ui->picture->contentsRect().size();
        QSize imageSize = m_originalPixmap.size().scaled(contentSize, Qt::KeepAspectRatio);

        // 计算居中偏移
        int xOffset = (contentSize.width() - imageSize.width()) / 2;
        int yOffset = (contentSize.height() - imageSize.height()) / 2;

        return QRect(
            labelPos.x() + xOffset,
            labelPos.y() + yOffset,
            imageSize.width(),
            imageSize.height()
        );
}
//将屏幕坐标系中的矩形区域转换为图像坐标系中的矩形区域
QRect TucamWidget::convertToImageRect(const QRect &screenRect) const {
    QRect displayArea = getImageDisplayArea();

       // Step 1: 将选区限制在图片显示区域内
       QRect validRect = screenRect.intersected(displayArea);

       // Step 2: 转换为相对于图片显示区域的坐标
       QRect relativeRect = validRect.translated(-displayArea.topLeft());

       // Step 3: 计算缩放比例（考虑非整数缩放）
       qreal scaleX = static_cast<qreal>(m_originalPixmap.width()) / displayArea.width();
       qreal scaleY = static_cast<qreal>(m_originalPixmap.height()) / displayArea.height();

       // Step 4: 转换为原始图片坐标系
       return QRect(
           qRound(relativeRect.x() * scaleX),
           qRound(relativeRect.y() * scaleY),
           qRound(relativeRect.width() * scaleX),
           qRound(relativeRect.height() * scaleY)
       );
}
//显示被裁剪部分的图片
void TucamWidget::handleCropCompleted(const QPixmap &cropped) {
    QPixmap displayPixmap = cropped.scaled(
            ui->picture->size(),
            Qt::KeepAspectRatio,  // 关键：保持比例
            Qt::SmoothTransformation
        );

        // 需要手动设置QLabel尺寸（避免自动填充）
        ui->picture->setFixedSize(displayPixmap.size());
        ui->picture->setPixmap(displayPixmap);

        // 调整布局（如果需要）
        adjustSize();
}
void TucamWidget::handleCropCanceled()
{
}

void TucamWidget::on_image_cut_clicked()
{
    activate();
}


//对图片进行旋转
void TucamWidget::on_image_normal_rotate_clicked()
{
    QMatrix matrix;
    matrix.rotate(90);
    ui->picture->setPixmap(ui->picture->pixmap()->transformed(matrix, Qt::SmoothTransformation));
}

void TucamWidget::on_image_anti_rotate_clicked()
{
    QMatrix matrix;
    matrix.rotate(-90);
    ui->picture->setPixmap(ui->picture->pixmap()->transformed(matrix, Qt::SmoothTransformation));
}

//调节图片亮度
void TucamWidget::on_image_brightness_slider_valueChanged(int value)
{
    if (originalimage.isNull()) {
            qDebug() << "未加载图片！";
        }
    else
    {     int constract = ui->image_contrast->value();
          QImage briImage = lightContrastImage(originalimage,value,constract/100.0);
          QPixmap pixmapPtr = QPixmap::fromImage(briImage);
          ui->picture->setPixmap(pixmapPtr.scaled(ui->picture->size(), Qt::KeepAspectRatio));
    }
}
QImage TucamWidget::lightContrastImage(const QImage &img,  int brightness, float Contrast)
    {
    QImage result = img.copy();
    if (result.format() != QImage::Format_ARGB32) {
        result = result.convertToFormat(QImage::Format_ARGB32);
    }

    for (int y = 0; y < result.height(); ++y) {
        QRgb* row = (QRgb*)result.scanLine(y);
        for (int x = 0; x < result.width(); ++x) {
            QColor color(row[x]);

            // 原始通道值（转换为浮点运算）
            double r = color.red();
            double g = color.green();
            double b = color.blue();

            // 对比度调整（浮点运算）
            r = (r - 128.0) * Contrast + 128.0;
            g = (g - 128.0) * Contrast + 128.0;
            b = (b - 128.0) * Contrast + 128.0;

            // 亮度调整（浮点运算）
            r += brightness;
            g += brightness;
            b += brightness;

            // 约束范围并转换回整数
            color.setRed(qBound(0, static_cast<int>(round(r)), 255));
            color.setGreen(qBound(0, static_cast<int>(round(g)), 255));
            color.setBlue(qBound(0, static_cast<int>(round(b)), 255));

            row[x] = color.rgba();
        }
    }
    return result;

    }

void TucamWidget::on_image_brightness_valueChanged(int arg1)
{
    if (originalimage.isNull()) {
            qDebug() << "未加载图片！";
        }
    else
    {     int constract = ui->image_contrast->value();
          QImage briImage = lightContrastImage(originalimage,arg1,constract/100.0);
          QPixmap pixmapPtr = QPixmap::fromImage(briImage);
          ui->picture->setPixmap(pixmapPtr.scaled(ui->picture->size(), Qt::KeepAspectRatio));
    }
}

void TucamWidget::on_image_contrast_slider_valueChanged(int value)
{
    if (originalimage.isNull()) {
            qDebug() << "未加载图片！";
        }
    else
    {
          QImage conImage = lightContrastImage(originalimage,ui->image_brightness->value(),value/100.0);
          QPixmap pixmapPtr = QPixmap::fromImage(conImage);
          ui->picture->setPixmap(pixmapPtr.scaled(ui->picture->size(), Qt::KeepAspectRatio));
    }
}

void TucamWidget::on_image_contrast_valueChanged(int arg1)
{
    if (originalimage.isNull()) {
            qDebug() << "未加载图片！";
        }
    else
    {
          QImage conImage = lightContrastImage(originalimage,ui->image_brightness->value(),arg1/100.0);
          QPixmap pixmapPtr = QPixmap::fromImage(conImage);
          ui->picture->setPixmap(pixmapPtr.scaled(ui->picture->size(), Qt::KeepAspectRatio));
    }
}
void TucamWidget::change()
{
    this->show();
    o.hide();
}
void TucamWidget::on_angle_value_slider_valueChanged(int value)
{
    ui->angle_value->setValue(value);//滑条带动数字框
}


void TucamWidget::on_angle_value_valueChanged(int value)
{
    ui->angle_value_slider->setValue(value);//数字框带动滑条
}
